package cn.wolfcode.wolf2w.business.service.Impl;

import cn.wolfcode.wolf2w.business.api.RemoteNoteService;
import cn.wolfcode.wolf2w.business.api.RemoteStrategyService;
import cn.wolfcode.wolf2w.business.api.domain.Note;
import cn.wolfcode.wolf2w.business.api.domain.Strategy;
import cn.wolfcode.wolf2w.business.query.SearchQuery;
import cn.wolfcode.wolf2w.business.service.ISearchService;
import cn.wolfcode.wolf2w.common.core.constant.SecurityConstants;
import cn.wolfcode.wolf2w.destination.RemoteDestinationServer;
import cn.wolfcode.wolf2w.destination.entity.TaDestination;
import cn.wolfcode.wolf2w.member.api.RemoteUserInfoService;
import cn.wolfcode.wolf2w.member.api.domain.UserInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class SearchServiceImpl implements ISearchService {

    @Autowired
    private ElasticsearchRestTemplate temple;

    @Autowired
    private RemoteStrategyService remoteStrategyService;

    @Autowired
    private RemoteNoteService remoteNoteService;

    @Autowired
    private RemoteUserInfoService remoteUserInfoService;

    @Autowired
    private RemoteDestinationServer remoteDestinationServer;

    @Override
//    public <T> Page<T> searchHighLight(String indexName, Class<T> clazz, SearchQuery qo, String... fields) {
    public <T> Page<T> searchHighLight(Class<T> mysqlClazz, Class<?> clazz, SearchQuery qo, String... fields) throws InvocationTargetException, IllegalAccessException {
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
//        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        builder.withQuery(
                QueryBuilders.multiMatchQuery(qo.getKeyword(),fields)
        );
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1,qo.getPageSize());
        builder.withPageable(pageRequest);
        HighlightBuilder.Field[] fs = new HighlightBuilder.Field[fields.length];
        for (int i = 0; i < fs.length; i++) {
            fs[i] = new HighlightBuilder.Field(fields[i])
                    .preTags("<span style='color:red;'>")
                    .postTags("</span>");
        }
        builder.withHighlightFields(fs);

        SearchHits<?> searchHits = temple.search(builder.build(), clazz);
        long total = searchHits.getTotalHits();

        List<T> list = new ArrayList<>();

        for (SearchHit<?> searchHit : searchHits) {

            String id = searchHit.getId();
            System.err.println("_id:" + id);

            T t = null;
            if(mysqlClazz == Strategy.class){
               t = (T) remoteStrategyService.getOne(Long.valueOf(id), SecurityConstants.INNER).getData();
            }else if(mysqlClazz == Note.class){
                t = (T) remoteNoteService.getOne(Long.valueOf(id), SecurityConstants.INNER).getData();
            }else if(mysqlClazz == UserInfo.class){
                t = (T) remoteUserInfoService.getOne(Long.valueOf(id), SecurityConstants.INNER).getData();
            }else if(mysqlClazz == TaDestination.class){
                t = (T) remoteDestinationServer.getById(Long.valueOf(id)).getData();
            }

//            Object content = searchHit.getContent();
//            T content = searchHit.getContent();
//            System.err.println(content);

            Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
            Set<String> keySet = highlightFields.keySet();
            for (String key : keySet) {
                List<String> stringList = highlightFields.get(key);
                StringBuffer sb = new StringBuffer();
                for (String s : stringList) {
                    sb.append(s);
                }
                String value = sb.toString();
                System.err.println("高亮的列：" + key + "高亮的值：" + value);

                BeanUtils.setProperty(t,key,value);


            }
            list.add(t);
        }

        System.err.println(list);
        return new PageImpl<T>(list,pageRequest,total);
    }
}
